// pages/tweet/detail/detail.js
import { 
  TWEET_DETAIL,
  TWEET_COMMENT_LIST,
  TWEET_COMMENT,
  TWEET_LIKE_LIST,
  TWEET_LIKE_REVERSE,
 } from "../../../request/api";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    item: {},
    tabIndex: 0,
    commentList: [],
    likeList: [],
    commentPageToken: '',
    likePageToken: '',
    defaultComment: {
      loadStatus: 2,
    },
    defaultLike: {
      loadStatus: 2,
    },
    winHeight: 0,
    hiddenmodalput: true,
    commentContent: '',
    replyId: 0,
    reAuthorId: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var height = getApp().globalData.screenHeight;
    if(options.tweet){
      var tweetObj = JSON.parse(decodeURIComponent(options.tweet));
      that.setData({
        winHeight: height,
        id: tweetObj.id,
        item: tweetObj,
      });
      this.loadMoreComment();
      this.loadMoreLike();
    } else if(options.id){
      that.setData({
        winHeight: height,
        id: options.id,
      });
      this.loadDetail();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: that.getShareTitle(), // 默认是小程序的名称(可以写slogan等)
      path: '/pages/tweet/detail/detail?id=' + that.data.id, // 默认是当前页面，必须是以‘/’开头的完整路径
      // imageUrl: '', //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
    };
    return shareObj;
  },

  onShareTimeline: function(){
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: that.getShareTitle(), // 默认是小程序的名称(可以写slogan等)
      query: 'id=' + that.data.id, //当前页面路径携带的参数
      // imageUrl: '', //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
    };
    return shareObj;
  },

  getShareTitle: function(){
    var userInfo = getApp().globalData.userInfo;
    var userName;
    if(userInfo){
      userName = userInfo.name || '有人';
    } else {
      userName = '有人';
    }
    var title = userName + '分享了动弹';
    return title;
  },

  /**
   * 截获竖向滑动
   */
  catchTouchMove:function(res){
    return false
  },
   /** 
  * 点击tab切换 
  */
 clickTab: function (e) {
    const edata = e.currentTarget.dataset;
    this.setData({
      tabIndex: edata.tabindex,
    })
  },

  _toUserProfile: function(e){
    var id = e.currentTarget.dataset.id;
    this.toPage('/pages/user/user?userId='+id);
  },
  toTransmit: function(){
    this.toPage('/pages/user/user?userId='+id);
  },
  toPage: function(url){
    wx.navigateTo({
      url: url,
    });
  },

  loadDetail: function(){
    TWEET_DETAIL({'id': this.data.id}).then(res => {
      if(res.data.code == 1){
        this.setData({
          id: res.data.result.id,
          item: res.data.result,
        });
        this.loadMoreComment();
        this.loadMoreLike();
      }
    });
  },

  loadMoreComment: function(e){
    TWEET_COMMENT_LIST({'pageToken': this.data.commentPageToken, 'sourceId': this.data.id}).then(res => {
      if(res.data.code == 1){
        var tempList = this.data.commentList;
        var list = res.data.result.items;
        if(this.data.commentPageToken.length > 0){
          list = tempList.concat(list);
        }
        this.data.item.commentCount = res.data.result.totalResults;
        this.setData({
          commentList: list,
          commentPageToken: res.data.result.nextPageToken,
          defaultComment: {
            loadStatus: res.data.result.responseCount < res.data.result.requestCount? 3: 2,
          }
        });
        console.log('commentList lenght = ' + this.data.commentList.length);
      } else {
        this.loadCommentStatus(2);
      }
    }).catch(err => {
      this.loadCommentStatus(2);
    });
  },
  loadCommentStatus: function(status){
    this.setData({
      defaultComment: {
        loadStatus: status,
      }
    });
  },
  refreshComment: function(e){
    this.data.commentPageToken = '';
    this.data.commentList = [];
    this.loadMoreComment();
  },

  loadMoreLike: function(e){
    TWEET_LIKE_LIST({'pageToken': this.data.likePageToken, 'sourceId': this.data.id}).then(res => {
      if(res.data.code == 1){
        var tempList = this.data.likeList;
        var list = res.data.result.items;
        if(this.data.likePageToken.length > 0){
          list = tempList.concat(list);
        }
        this.data.item.likeCount = res.data.result.totalResults;
        this.setData({
          likeList: list,
          likePageToken: res.data.result.nextPageToken,
          defaultLike: {
            loadStatus: res.data.result.responseCount < res.data.result.requestCount? 3: 2,
          }
        });
        console.log('likeList lenght = ' + this.data.likeList.length);
      } else {
        this.loadLikeStatus(2);
      }
    }).catch(err => {
      this.loadLikeStatus(2);
    });
  },
  refreshLike: function(e){
    this.data.likePageToken = '';
    this.data.likeList = [];
    this.loadMoreLike();
  },
  loadLikeStatus: function(status){
    this.setData({
      defaultLike: {
        loadStatus: status,
      }
    });
  },

  reverseTweetLike: function(){
    var sourceId = this.data.id;
      TWEET_LIKE_REVERSE({'sourceId': sourceId}).then(res => {
        if(res.data.code == 1){
          var temp = this.data.item;
          temp.liked = res.data.result.liked;
          temp.likeCount = res.data.result.likeCount;
          this.setData({
            item: temp,
          });
          this.refreshLike();
        }
      }).catch(err =>{})
  },

  submitComment: function(id, replyId, reAuthorId, type, content){
    wx.showLoading({
      title: '正在提交...',
    });
    TWEET_COMMENT({
      'sourceId': id,
      // 'replyId': replyId,
      // 'reAuthorId': reAuthorId,
      // 'type': type,
      'content': content,
    }).then(res => {
      wx.hideLoading({
        success: (res) => {},
      });
      this.showTips(res.data.message);
      if(res.data.code == 1){
        this.refreshComment();
      }
    }).catch(err => {
      wx.hideLoading({
        success: (res) => {},
      });
      this.showTips("评论失败");
    });
  },

  showCommentInput: function () {
    if(!getApp().globalData.versionCheckPassed){
      this.showTips('暂不支持评论');
      return;
    }
    if (!this.checkLogin()) {
      return;
    }
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput,
    });
  },

  //取消按钮
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },

  //确认
  confirm: function () {
    if(this.data.commentContent.length == 0){
      this.showTips('请输入评论内容');
      return;
    }
    this.submitComment(this.data.id, this.data.replyId, this.data.reAuthorId, this.data.type, this.data.commentContent);
    this.setData({
      hiddenmodalput: true,
    });
  },

  inputChange: function(e){
    this.data.commentContent = e.detail.value;
  },


  showTips: function (msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  },

  checkLogin: function () {
    var app = getApp();
    if (!app.globalData.isLogin) {
      wx.showModal({
        content: '您还没有登录，请登录',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/account/login/login',
            });
          } else if (res.cancel) {

          }
        }
      });
      return false;
    } else {
      return true;
    }
  }
})